/**
 * @file: 添加/编辑用户弹窗
 * @author: Lengxx
 * @date: 2024-06-19
 */
<template>
  <BasicModal 
  :width="400"
  :title="isEdit ? '编辑用户' : '添加用户'"
  v-bind="$attrs"
  @register="register"
  @ok="onModalSubmit"
  :loading="loading || editLoading"
  >
    <Form 
    autocomplete="off"
    :labelCol="{ span: 6 }"
    :wraperCol="{ span: 18 }"
    >
      <FormItem label="用户名" name="username" v-bind="validateInfos.username" >
        <Input placeholder="请输入用户名" v-model:value="formState.username" :disabled="isEdit" />
      </FormItem>
      <FormItem v-if="isEdit" label="密码" name="password" >
        <Input type="password" placeholder="请输入密码" v-model:value="formState.password" :disabled="isEdit" />
      </FormItem>
      <FormItem v-else label="密码" name="password" v-bind="validateInfos.password" >
        <Input type="password" placeholder="请输入密码" v-model:value="formState.password" />
      </FormItem>
      <FormItem label="昵称" name="nickname" v-bind="validateInfos.nickname" >
        <Input placeholder="请输入昵称" v-model:value="formState.nickname"  />
      </FormItem>
      <FormItem label="联系电话" name="phone" >
        <Input placeholder="请输入联系电话" v-model:value="formState.phone" />
      </FormItem>
      <FormItem label="头像" name="avatar" >
        <Upload 
        accept=".jpg,.png,.jpeg"
        list-type="picture-card"
        :show-upload-list="false"
        :beforeUpload="onBeforeUpload"
        >
          <img v-if="formState.avatar" width="100" height="100" :src="formState.avatar" alt="avatar" />
          <div v-else>
            <Button type="text" :icon="h(PlusOutlined)"></Button>
            <div class="ant-upload-text">上传</div>
          </div>
        </Upload>
      </FormItem>
    </Form>
  </BasicModal>
</template>

<script lang="ts" setup>
import { get } from 'lodash-es'
import { ref, reactive, h } from 'vue'
import * as api from '@/api/user'
import { getLoginPublicKey } from '@/api/login'
import { AddUserRules } from '../tableOpts';
import { ModalTypeEnum } from '@/enums/appEnum';
import { useRequest } from '@vben/hooks'
import { useMessage } from '@/hooks/web/useMessage'
import { Form, FormItem, Input, Upload, Button } from 'ant-design-vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { FileType } from 'ant-design-vue/es/upload/interface';
import { PlusOutlined } from '@ant-design/icons-vue'
import { encryptPwd } from '@/utils/auth'
import { useUserStore } from '@/store/modules/user'

const emits = defineEmits(['submit'])

const { loading, runAsync: addUser } = useRequest(api.addUser, { manual: true })
const { loading: editLoading, runAsync: updateUser } = useRequest(api.updateUserInfo, { manual: true })

const useForm = Form.useForm;

const userStore = useUserStore();
const { createMessage } = useMessage()

const isEdit = ref(false);
const userId = ref('');

const formState = reactive<Partial<api.IAddUser>>({
  username: '',
  password: '',
  phone: '',
  avatar: '',
  nickname: '',
})

const { validateInfos, validate, resetFields } = useForm(formState, AddUserRules)

const [register] = useModalInner(data => {
  const modalType = get<ModalTypeEnum>(data, 'modalType', ModalTypeEnum.Add);

  if (modalType == ModalTypeEnum.Edit) {
    isEdit.value = true;
    const user = get(data, 'record') as api.IAddUser & { id: string };
    if (user) {
      const {avatar, username, password, nickname, phone, id} = user;
      formState.username = username;
      formState.password = password;
      formState.avatar = avatar;
      formState.nickname = nickname;
      formState.phone = phone;
      userId.value = id;
    }

  } else if (modalType == ModalTypeEnum.Add) {
    isEdit.value = false;
    resetFields();
  }
})

/** 上传头像 */
function onBeforeUpload(file: FileType) {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    formState.avatar = reader.result as string;
  }
  return false
}

/** 提交 */
async function onModalSubmit() {
  await validate<api.IAddUser>();
  const user = {...formState} as api.IAddUser;

  if (isEdit.value) {
    if (formState) {
      const data: api.IUserInfo = {
        id: userId.value,
        nickname: user.nickname,
        phone: user.phone,
        avatar: user.avatar,
      }
      await updateUser(data);
      createMessage.success('编辑成功');
      emits('submit');
    }
  } else {
    await addUser(user);
    createMessage.success('添加成功');
    emits('submit');
  }
}

</script>

